// 声明全局变量存放服务器需求的图片地址格式
let advimgsrc
const form = layui.form
const query = {
  advimgdesc: '',
  advimgpos: '',
  page: '',
  limit: ''
}

// 封装渲染函数
async function getAdvi() {
  const { data: { data } } = await axios.get('/ydd_advimg/list', {
    params: query
  })
  // console.log(data);
  document.querySelector('#tbody').innerHTML = data.data.map((item, index) => `
  <tr>
              <td>${index}</td>
              <td>${item.advposname}</td>
              <td>${item.advimgdesc}</td>
              <td><img src="http://124.223.14.236:8060/${item.advimgsrc}" alt=""></td>
              <td>${item.advimglink}</td>
              <td>
                <button type="button" data-id=${item.id}  class="layui-btn layui-btn-xs btn_edit" >编辑</button>
                <button type="button" data-id=${item.id} class="layui-btn layui-btn-xs layui-btn-danger btn_delete">删除</button>
              </td>
            </tr>
  `).join('')

  document.querySelector('#adviSel').innerHTML = `<option value="">请选择</option>` + data.data.map(item => `
  <option value="${item.advimgpos}">${item.advposname}</option>
  `).join('')
  form.render('select')
  renderPage(data.count)
}

getAdvi()

// 用layui分页
const laypage = layui.laypage
function renderPage(total) {
  laypage.render({
    elem: 'page-box',
    count: total,
    curr: query.page,//显示高亮
    limit: query.limit,
    limits: [1, 2, 3, 5, 8, 10],
    layout: ['count', 'limit', 'prev', 'next', 'page', 'skip'],
    jump: function (obj, first) {
      // jump触发的时机：分页渲染的时候也会触发,但是触发时，first的值不同,所以点击分页时log会执行两次
      //obj包含了当前分页的所有参数，比如：
      // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
      // console.log(obj.limit); //得到每页显示的条数
      // console.log(first);

      query.page = obj.curr
      query.limit = obj.limit
      //首次不执行
      if (!first) {
        //do something
        getAdvi()
      }
    }
  })
}


// 搜索功能
document.querySelector('#adviSearch').addEventListener('click', function (e) {

  // e.preventDefault()

  query.advimgdesc = document.querySelector('#inpAdviDes').value

  query.advimgpos = document.querySelector('#adviSel').value
  // console.log(query);
  getAdvi()
  form.render()
})


// 防抖函数
function debounce(callback, time) {
  let timerId = null
  // 返回值：函数
  return function () {
    if (timerId) clearTimeout(timerId)
    timerId = setTimeout(() => {
      // 调用callback 这里的callback 就是相当于调用 getValue
      callback()

    }, time)
  }
}

// 动态搜索功能（防抖版）
$('#inpAdviDes').on('input', debounce(function () {
  query.advimgdesc = document.querySelector('#inpAdviDes').value
  query.advimgpos = document.querySelector('#adviSel').value
  // console.log(query);
  getAdvi()
  form.render()
}, 1000))
// 选项框动态选择
form.on('select(adviSel)', async function () {
  query.advimgdesc = document.querySelector('#inpAdviDes').value
  query.advimgpos = document.querySelector('#adviSel').value
  // console.log(query);
  const { data: { data } } = await axios.get('/ydd_advimg/list', {
    params: query
  })
  document.querySelector('#tbody').innerHTML = data.data.map((item, index) => `
  <tr>
              <td>${index}</td>
              <td>${item.advposname}</td>
              <td>${item.advimgdesc}</td>
              <td><img src="http://124.223.14.236:8060/${item.advimgsrc}" alt=""></td>
              <td>${item.advimglink}</td>
              <td>
                <button type="button" data-id=${item.id} data-advimgpos=${item.advimgpos} class="layui-btn layui-btn-xs btn_edit" >编辑</button>
                <button type="button" data-id=${item.id} class="layui-btn layui-btn-xs layui-btn-danger btn_delete">删除</button>
              </td>
            </tr>
  `).join('')
  form.render()
})

// 添加功能弹出窗渲染
let adviIndex
document.querySelector('#adviAdd').addEventListener('click', async function (e) {
  adviIndex = layer.open({
    content: `<form id="addForm" lay-filter="formAdd" class="layui-form">
      <!-- 第一行 广告位名称 -->
      <div class="layui-form-item">
  <label class="layui-form-label">广告位</label>
  <div class="layui-input-block">
    <select name="advimgpos" lay-verify="required" id="adviSel2">
    </select>
  </div>
</div>
      <!-- 第二行 广告位描述  -->
      <div class="layui-form-item">
        <label class="layui-form-label">广告位描述</label>
        <div class="layui-input-block">
          <input type="text" name="advimgdesc" required lay-verify="required" placeholder="请输入标题" autocomplete="off"
            class="layui-input">
        </div>
      </div>
      <!-- 第三行 广告位链接  -->
      <div class="layui-form-item">
        <label class="layui-form-label">广告位链接</label>
        <div class="layui-input-block">
          <input type="text" name="advimglink" required lay-verify="required" placeholder="请输入标题" autocomplete="off"
            class="layui-input">
        </div>
      </div>
      <!-- 第三行 img显示  -->
      <div class="layui-form-item">
        <label class="layui-form-label">广告图</label>
          <img id="imgEdit" src="" alt="" style="width:100px;height:100px;">
      </div>
      <!-- 第三行 广告图修改  -->
      <div class="layui-form-item">
        <label class="layui-form-label">广告图修改</label>
        <div class="layui-input-block">
        <button id="addButton" type="button" class="layui-btn">选择文件</button>
          <input style="display:none;" type="file" name="advimgsrc" required lay-verify="required" accept="image/jpeg,image/png,image/gif,image/bmp" autocomplete="off"
            class="layui-input" id="addFile">
        </div>
      </div>
      <!-- 第三行 按钮 -->
      <div class="layui-form-item">
        <div class="layui-input-block">
          <button class="layui-btn" lay-submit lay-filter="formDemo">确认</button>
          <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
      </div>
    </form>`,//内容
    type: 1,//弹出层类型
    title: '添加广告位',//标题
    area: ['500px', '250px']//宽高
  })
  const { data: { data } } = await axios.get('/ydd_advimg/list', {
    params: query
  })
  // console.log(data);
  const selArr = data.data.map(item => `
  <option value="${item.advimgpos}">${item.advposname}</option>
  `).join('')
  // console.log(selArr)
  document.querySelector('#adviSel2').innerHTML = selArr

  form.render()// 渲染全部表单
})


// 给文件选择框注册change事件，获取服务器需求的图片地址
// 用设置的全局变量接收新的图片地址

function imgChange(idName) {
  $('body').on('change', `#${idName}`, async function (e) {
    console.log(e);

    // files[0]为文件
    const files = document.querySelector(`#${idName}`).files[0]

    const fd = new FormData()
    fd.append("file", files)
    const { data: { data: { savePath } } } = await axios.post(`/common/upload?type=images`, fd, {
      headers: {
        "Content-Type": "multipart/form-data"
      }
    })
    advimgsrc = savePath

    // 用于显示图片
    document.querySelector('#imgEdit').src = `http://124.223.14.236:8060/${advimgsrc}`
  })
}

imgChange('addFile')

// 添加功能
$('body').on('submit', '#addForm', async function (e) {
  e.preventDefault()
  // console.log(e);
  const data = serialize(document.querySelector('#addForm'), { hash: true })
  data.advimgsrc = advimgsrc
  console.log(data);

  const addAdvi = await axios.post('/ydd_advimg/add', data)
  if (!addAdvi.data.errno)
    // console.log(addAdv);
    layer.msg('添加成功')
  layer.close(adviIndex)
  getAdvi()

})

// 编辑功能
// 编辑功能弹出框渲染
let adviIndex2
document.querySelector('#tbody').addEventListener('click', async function (e) {
  console.log(e);
  if (e.target.classList.contains('btn_edit')) {
    adviIndex2 = layer.open({
      content: `<form id="editForm" lay-filter="formEdit" class="layui-form">
      <!-- 第一行 广告位 -->
      <div class="layui-form-item">
  <label class="layui-form-label">广告位</label>
  <div class="layui-input-block">
    <select name="advimgpos" lay-verify="required" id="editSel">
    </select>
  </div>
</div>
      <!-- 第二行 广告位描述  -->
      <div class="layui-form-item">
        <label class="layui-form-label">广告位描述</label>
        <div class="layui-input-block">
          <input type="text" name="advimgdesc" required lay-verify="required" placeholder="请输入标题" autocomplete="off"
            class="layui-input">
        </div>
      </div>
      <!-- 第三行 广告位链接  -->
      <div class="layui-form-item">
        <label class="layui-form-label">广告位链接</label>
        <div class="layui-input-block">
          <input type="text" name="advimglink" required lay-verify="required" placeholder="请输入标题" autocomplete="off"
            class="layui-input">
        </div>
      </div>

      <!-- 第三行 广告图  -->
      <div class="layui-form-item">
        <label class="layui-form-label">广告图</label>
          <img id="imgEdit" src="" alt="" style="width:100px;height:100px;">
      </div>

      <!-- 第三行 广告图选择  -->
      <div class="layui-form-item">
        <label class="layui-form-label">广告图选择</label>
        <div class="layui-input-block">
        <button id="editButton" type="button" class="layui-btn">选择文件</button>
          <input type="file" style="display:none;"  accept="image/jpeg,image/png,image/gif,image/bmp" autocomplete="off"
            class="layui-input" id="editFile">
        </div>
      </div>
      <!-- 第三行 存放img地址  -->
      <div class="layui-form-item" style="display:none;">
        <label class="layui-form-label">default</label>
        <div class="layui-input-block">
          <input type="text" name="advimgsrc" required lay-verify="required" placeholder="请输入标题" autocomplete="off"
            class="layui-input">
        </div>
      </div>

      <!-- 第三行 id  -->
      <div class="layui-form-item" style="display:none;">
        <label class="layui-form-label">id</label>
        <div class="layui-input-block">
          <input type="text" name="id" required lay-verify="required" placeholder="请输入标题" autocomplete="off"
            class="layui-input">
        </div>
      </div>
      <!-- 第三行 default  -->
      <div class="layui-form-item" style="display:none;">
        <label class="layui-form-label">default</label>
        <div class="layui-input-block">
          <input type="text" name="default_data" required lay-verify="required" placeholder="请输入标题" autocomplete="off"
            class="layui-input">
        </div>
      </div>
      <!-- 第三行 按钮 -->
      <div class="layui-form-item">
        <div class="layui-input-block">
          <button class="layui-btn" lay-submit ">确认</button>
          <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
      </div>
    </form>`,//内容
      type: 1,//弹出层类型
      title: '添加广告位',//标题
      area: ['500px', '250px']//宽高
    })

    // 渲染选择框
    const { data: { data } } = await axios.get('/ydd_advimg/list', {
      params: query
    })
    console.log(1);
console.log(data);
    const editSelArr = data.data.map(item => `
  <option value="${item.advimgpos}">${item.advposname}</option>
  `).join('')

    document.querySelector('#editSel').innerHTML = editSelArr

    // 保证点开为当前的广告位（原版未做）
   
    form.render()
    const id1 = e.target.dataset.id
    const adviCom = await axios.get('ydd_advimg/rowInfo', { params: { id: id1 } })
    document.querySelector('#editSel').value = adviCom.data.data.advimgpos
    console.log(adviCom);
    const { advimgdesc, advimglink, advimgpos, advimgsrc, default_data, id } = adviCom.data.data

    form.val('formEdit', { advimgdesc, advimglink, advimgsrc, default_data, id })
    document.querySelector('#imgEdit').src = `http://124.223.14.236:8060/` + adviCom.data.data.advimgsrc

    form.render()
  }
})


// 两个submit会冲突,被迫用JQ写
imgChange('editFile')
$('body').on('submit', '#editForm', async function (e) {

  e.preventDefault()
  const data = serialize(document.querySelector('#editForm'), { hash: true })
  if (document.querySelector('#editFile').files[0]) {
    data.advimgsrc = advimgsrc
  }
  console.log(data);
  const editAdvi = await axios.post('ydd_advimg/update', data)
  if (!editAdvi.data.errno)

    layer.msg('编辑成功')
  layer.close(adviIndex2)
  getAdvi()
  form.render()

})

// 删除功能
document.querySelector('#tbody').addEventListener('click', function (e) {
  if (e.target.classList.contains('btn_delete')) {
    layer.confirm('确认要删除吗', async function (index) {
      const id = e.target.dataset.id
      console.log(id);
      const data = await axios.get('/ydd_advimg/del', { params: { id } })
      console.log(data);
      if (data.data.errno) {
        return layer.msg(data.data.errmsg)
      }
      layer.msg('删除成功')
      layer.close(index)
      getAdvi()
    })

  }
})

// 图片点击放大功能
let imgAlert
$('body').on('click', '#imgEdit', function () {
  const src = document.querySelector('#imgEdit').src
  imgAlert = adviIndex2 = layer.open({
    content: `
    <img  src="${src}" alt="" style="width:470px;height:190px;">
    `,//内容
    type: 1,//弹出层类型
    title: '图片详情',//标题
    area: ['500px', '250px']//宽高
  })
})

// 美化选择图片按钮
$('body').on('click', '#addButton', function () {
  $('#addFile').click()
})
$('body').on('click', '#editButton', function () {
  $('#editFile').click()
})
